  <?php
  require_once('recaptchalib.php');
  require_once('backend/modules/Backend.php');
  require_once('backend/modules/Database.php');
  $privatekey = "6LeqoMMSAAAAAPMTl9p4tmZBS6V9QdhaUv6-yHbT";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    
############################
## Timestamp constants
############################
$ONE_YEAR = 10000000000;
$ONE_MONTH = 100000000;

############################
## Check requirements
############################
while ($script->user['name']) {
    if (!isset($script->events[$_GET['event']])) {
        echo "<div class='error'>There is no event matching the given ID.</div>";
        break;
    }

    echo "<h2>Analysis", ($script->user['name'] == 'Shanel' ? '&#9829;' : ''), "</h2>";

    /***************
     * Validate or default wiki
     ***************/
    /* incorrect wiki specified */
    if ($script->wiki && isset($script->event['only_db']) && $script->wiki != $script->event['only_db']) {
        echo "<div class='error'>Account must be on {$script->wikis[$script->event['only_db']]}. Select 'auto-select wiki' above to select the correct wiki.</div>";
        break;
    }

    /* select (or default) wikis */
    if (isset($script->event['only_db'])) {
        $script->event['default_db'] = $script->event['only_db'];
    }
    if (!$script->default_wiki($script->event['default_db'])) {
        $script->msg("Selection failed, aborted.");
        break;
    }

    /* validate user exists */
    if (!isset($script->user['id'])) {
        echo "<div class='error'>{$script->user['name']} does not exist on {$script->wiki}.</div>";
        break;
    }

    /***************
     * Verify requirements
     ***************/
    switch ($script->event['id']) {
        ############################
        ## 2011 Commons Picture of the Year 2010
        ############################
        case 0:
            $script->printWiki();
            $age_okay = false;
            $edits_okay = false;
            do {
                $script->eligible = true;
            
                ########
                ## registered < 2011-Jan-01
                ########
                if(!$age_okay) {
                    $age_okay = $script->condition(
                        $date_okay = ($script->user['registration_raw'] < 20110101000000),
                        "has an account registered before 01 January 2011 (registered {$script->user['registration']})...",
                        "does not have an account registered before 01 January 2011 (registered {$script->user['registration']})."
                    );
                }

                ########
                ## >= 200 edits before 2011-Jan-01
                ########
                if(!$edits_okay) {
                    $edits = $script->edit_count(NULL, 20110101000000);
                    $edits_okay = $script->condition(
                        $edits_okay = ($edits >= 200),
                        "has 200 edits before 01 January 2011 (has {$edits})...",
                        "does not have 200 edits before 01 January 2011 (has {$edits})."
                    );
                }
                
                $script->eligible = ($age_okay && $edits_okay);
            }
            while (!$script->eligible && $script->get_next());
            break;
    /*
        ############################
        ## 2011 steward confirmations
        ############################
        case 15:
            ########
            ## Has an account on Meta
            ########
            $script->msg('Global requirements:', 'is-wiki');
            if ($script->wiki == 'metawiki_p' || in_array('metawiki_p', $script->queue)) {
                $on_meta = true;
            }
            else {
                $script->db->Connect('metawiki_p');
                $script->db->Query(
                    "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                    Array($script->user['name'])
                );
                $on_meta = $script->db->fetchColumn();
                $script->db->ConnectPrevious();
            }

            $script->condition(
                $on_meta,
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            if (!$script->eligible) {
                break;
            }

            ########
            ## Check local requirements
            ########
            $script->printWiki();
            do {
                ########
                ## >=1 edits before 01 February 2011
                ########
                $edits = $script->edit_count(NULL, 20110201000000);
                $script->condition(
                    $edits >= 1,
                    "has one edit before 01 February 2011 (has {$edits})...",
                    "does not have one edit before 01 February 2011 (has {$edits})."
                );
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2011 steward elections
        ############################
        case 14:
            ########
            ## Has an account on Meta
            ########
            $script->msg('Global requirements:', 'is-wiki');
            if ($script->wiki == 'metawiki_p' || in_array('metawiki_p', $script->queue)) {
                $on_meta = true;
            }
            else {
                $script->db->Connect('metawiki_p');
                $script->db->Query(
                    "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                    Array($script->user['name'])
                );
                $on_meta = $script->db->fetchColumn();
                $script->db->ConnectPrevious();
            }

            $script->condition(
                $on_meta,
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            if (!$script->eligible) {
                break;
            }

            ########
            ## Has a global account
            ########
            $script->condition(
                $script->is_global(),
                "has a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>...",
                "does not have a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a> (<strong>optional</strong>)...",
                "",
                "is-warn"
            );
            $script->eligible = true;

            ########
            ## Check local requirements
            ########
            $script->printWiki();

            /* set messages for global accounts */
            if ($script->unified) {
                $edits_fail_append = "However, edits will be combined with other unified wikis.";
                $edits_fail_attrs = "is-warn";
            }
            else {
                $edits_fail_append = '';
                $edits_fail_attrs = '';
            }

            /* check requirements */
            $prior_edits = 0;
            $recent_edits = 0;
            $combining = false;
            $marked_bot = false;
            do {
                ########
                ## Should not be a bot
                ########
                $is_bot = $script->has_role('bot');
                $script->condition(
                    !$is_bot,
                    "no bot flag...",
                    "has a bot flag &mdash; the global account must not be primarily automated (bot), but I can't check this so won't mark ineligible.",
                    "",
                    "is-warn"
                );
                $script->eligible = true;
                if ($is_bot && !$marked_bot) {
                    $script->event['append_eligible'] = "<br /><strong>Note:</strong> this account is marked as a bot on some wikis. If it is primarily an automated account (bot), it is <em>not</em> eligible.";
                    $marked_bot = true;
                }

                ########
                ## >=600 edits before 01 November 2010
                ########
                $edits = $script->edit_count(NULL, 20101101000000);
                $prior_edits += $edits;
                $script->condition(
                    $edits >= 600,
                    "has 600 edits before 01 November 2010 (has {$edits})...",
                    "does not have 600 edits before 01 November 2010 (has {$edits}). {$edits_fail_append}",
                    "",
                    $edits_fail_attrs
                );
                if (!$script->eligible) {
                    if (!$script->unified) {
                        continue;
                    }
                    $combining = true;
                }

                ########
                ## >=50 edits between 2010-Aug-01 and 2010-Jan-31
                ########
                $edits = $script->edit_count(20100800000000, 20110200000000);
                $recent_edits += $edits;
                $script->condition(
                    $edits >= 50,
                    "has 50 edits between 01 August 2010 and 31 January 2011 (has {$edits})...",
                    "does not have 50 edits between 01 August 2010 and 31 January 2011 (has {$edits}). {$edits_fail_append}",
                    "",
                    $edits_fail_attrs
                );
                if (!$script->eligible) {
                    if (!$script->unified) {
                        continue;
                    }
                    $combining = true;
                }


                ########
                ## Exit conditions
                ########
                $script->eligible = $prior_edits >= 600 && $recent_edits >= 50;

                /* unified met requirements */
                if ($script->unified && !$script->IsQueueEmpty()) {
                    if ($script->eligible) {
                        break;
                    }
                    $combining = true;
                }
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2011 steward elections (candidates)
        ############################
        case 13:
            ########
            ## Has an account on Meta
            ########
            $script->msg('Global requirements:', 'is-wiki');
            if ($script->wiki == 'metawiki_p' || in_array('metawiki_p', $script->queue)) {
                $on_meta = true;
            }
            else {
                $script->db->Connect('metawiki_p');
                $script->db->Query(
                    "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                    Array($script->user['name'])
                );
                $on_meta = $script->db->fetchColumn();
                $script->db->ConnectPrevious();
            }

            $script->condition(
                $on_meta,
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            if (!$script->eligible) {
                break;
            }


            ########
            ## Has a global account
            ########
            $script->condition(
                $script->is_global(),
                "has a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>...",
                "does not have a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>..."
            );
            if (!$script->eligible) {
                break;
            }

            ########
            ## Check local requirements
            ########
            /* prefetch Meta rights changes */
            $script->db->Connect('metawiki_p');
            $script->db->Query('SELECT log_title, log_timestamp, log_params, log_comment FROM metawiki_p.logging_ts_alternative WHERE log_type = \'rights\' AND log_title LIKE ?', array(str_replace(' ', '_', $script->user['name']) . '@%')); // logging table randomly uses underscores
            $logTemp = $script->db->fetchAllAssoc();
            $script->db->ConnectPrevious();

            $logMeta = array();
            foreach ($logTemp as $k => $item)
            {
                if (!array_key_exists($item['log_title'], $logMeta)) {
                    $logMeta[$item['log_title']] = array();
                }
                array_push($logMeta[$item['log_title']], $item);
            }
            unset($logTemp);

            /* check local requirements */
            $minDurationMet = false;
            $script->printWiki();
            do {
                $script->eligible = true;

                ########
                ## Registered before 2010-Mar-29
                ########
                $script->condition(
                    $script->user['registration_raw'] < 20100829000000,
                    "has an account registered before 29 August 2010 (registered {$script->user['registration']})...",
                    "does not have an account registered before 29 August 2010 (registered {$script->user['registration']})."
                );

                ########
                ## Must have been a sysop for three months
                ########
                if (!$minDurationMet) {
                    /* get combined logs */
                    $script->db->Query('SELECT log_timestamp, log_params, log_comment FROM ' . $script->wiki . '.logging_ts_alternative WHERE log_type = \'rights\' AND log_title = ?', array(str_replace(' ', '_', $script->user['name']))); // log table randomly uses underscores
                    $local = $script->db->fetchAllAssoc();

                    $meta = $logMeta[$script->user['name'] . '@' . substr($script->wiki, 0, -2)];
                    if (isset($meta)) {
                        $merged = array_merge($local, $meta);
                    }
                    else
                    {
                        $merged = $local;
                    }

                    $logs = array();
                    foreach ($merged as $k => $item)
                    {
                        /* wonky logic ahead: the roles are stored four different ways in the DB */
                        if ($item['log_params'] != '') {
                            $pos = strpos($item['log_params'], "\n");
                            if ($pos === false) {
                                $logs[$item['log_timestamp']] = $item['log_params'];
                            } // was stored as "old\nnew"
                            else
                            {
                                $logs[$item['log_timestamp']] = substr($item['log_params'], $pos);
                            } // was stored as "new,roles"
                        }
                        else
                        {
                            $logs[$item['log_timestamp']] = $item['log_comment'];
                        } // 2006 and earlier, was stored as "+new"
                    }
                    ksort($logs);
                    unset($local, $meta, $merged);

                    /* get longest duration as sysop */
                    $maxDuration = 0;
                    $curStart = 0;
                    $curSysop = false; // whether the user is currently a sysop
                    foreach ($logs as $timestamp => $roles)
                    {
                        /* is the user a sysop as of this timestamp? */
                        $curSysop = (strpos($roles, "sysop") !== false);

                        /* does not have flag */
                        if (!$curSysop) {
                            $curStart = 0;
                            continue;
                        }

                        /* has flag */
                        if ($curStart == 0) {
                            $curStart = $timestamp;
                        }
                        $curDuration = ($timestamp - $curStart);
                        if ($curDuration > $maxDuration) {
                            $maxDuration = $curDuration;
                        }
                    }

                    /* if currently an admin, add remaining time */
                    if ($curSysop && $maxDuration == $curDuration) {
                        $curDate = gmdate('YmdHis');
                        $maxDuration = $curDate - $curStart;
                    }

                    /* calculate number of months */
                    $months = 0;
                    $readableDuration = '';

                    if ($maxDuration == 0) {
                        $readableDuration = 'never flagged';
                    }
                    else {
                        if ($maxDuration < $ONE_MONTH) {
                            $readableDuration = 'longest flag duration is less than a month';
                        }
                        else
                        {
                            $years = $maxDuration / $ONE_YEAR;
                            $months = ($maxDuration % $ONE_YEAR) / $ONE_MONTH;
                            $months = ($years * 12) + $months;

                            $readableDuration = 'longest flag duration is ' . round($months, 1) . ' months';
                        }
                    }

                    /* check requirement */
                    $minDurationMet = ($months >= 3);
                    $script->condition(
                        $minDurationMet,
                        'was flagged as an administrator for a continuous period of at least three months (' . $readableDuration . ')...',
                        'was not flagged as an administrator for a continuous period of at least three months (' . $readableDuration . ').'
                    );
                    if ($maxDuration > 0) {
                        $script->msg('<small>(Currently ' . ($curSysop ? '' : 'not') . ' an admin.)</small>');
                    }
                    if ($minDurationMet && !$script->IsQueueEmpty() && !$script->eligible) {
                        $script->msg('<span style="font-size:0.9em;">(Also, I won\'t check this requirement again to save time.)</span>');
                    }
                }
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2010 enwiki arbcom elections
        ############################
        case 12:
            $script->printWiki();

            ########
            ## >=150 main-NS edits before 2010-Nov-02
            ########
            /* SQL derived from query written by [[en:user:Cobi]], from < http://toolserver.org/~sql/sqlbot.txt > */
            $script->db->Query(
                "SELECT data.count FROM ("
                . "SELECT IFNULL(page_namespace, 0) AS page_namespace, IFNULL(SUM(rev.count), 0) AS count FROM {$script->wiki}.page, ("
                . "SELECT rev_page, COUNT(*) AS count FROM {$script->wiki}.revision WHERE rev_user=? AND rev_timestamp<? GROUP BY rev_page"
                . ") AS rev WHERE rev.rev_page=page_id AND page_namespace=0"
                . ") AS data, toolserver.namespace AS toolserver WHERE ns_id=page_namespace AND dbname='enwiki_p'",
                Array($script->user['id'], 20101102000000)
            );
            $edits = $script->db->fetchColumn();

            $script->condition(
                $edits >= 150,
                "has 150 main-namespace edits on or before 01 November 2010 (has {$edits})...",
                "does not have 150 main-namespace edits on or before 01 November 2010 (has {$edits})."
            );
            

            ########
            ## Not currently blocked
            ########
            $script->condition(
                !$script->currently_blocked(),
                "not currently blocked...",
                "must not be blocked during at least part of election (verify <a href='http://en.wikipedia.org/wiki/Special:Log/block?user=" . urlencode($script->user['name']) . "' title='block log'>block log</a>)."
            );
            break;


        ############################
        ## 2010 steward elections, September
        ############################
        case 11:
            $start_date = 20100901000000;

            ########
            ## Has an account on Meta
            ########
            $script->msg('Global requirements:', 'is-wiki');
            if ($script->wiki == 'metawiki_p' || in_array('metawiki_p', $script->queue)) {
                $on_meta = true;
            }
            else {
                $script->db->Connect('metawiki_p');
                $script->db->Query(
                    "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                    Array($script->user['name'])
                );
                $on_meta = $script->db->fetchColumn();
                $script->db->ConnectPrevious();
            }

            $script->condition(
                $on_meta,
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            if (!$script->eligible) {
                break;
            }

            ########
            ## Has a global account
            ########
            $script->condition(
                $script->is_global(),
                "has a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>...",
                "does not have a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a> (<strong>optional</strong>)...",
                "",
                "is-warn"
            );


            ########
            ## Check local requirements
            ########
            $script->printWiki();

            /* set messages for global accounts */
            if ($script->unified) {
                $edits_fail_append = "However, edits will be combined with other unified wikis.";
                $edits_fail_attrs = "is-warn";
            }
            else {
                $edits_fail_append = '';
                $edits_fail_attrs = '';
            }

            /* check requirements */
            $prior_edits = 0;
            $recent_edits = 0;
            $combining = false;
            $marked_bot = false;
            do {
                ########
                ## Should not be a bot
                ########
                $script->condition(
                    !$script->has_role('bot'),
                    "no bot flag...",
                    "has a bot flag &mdash; the global account must not be primarily automated (bot), but I can't check this so won't mark ineligible.",
                    "",
                    "is-warn"
                );
                $script->eligible = true;
                if ($script->has_role('bot') && !$marked_bot) {
                    $script->event['append_eligible'] = "<br /><strong>Note:</strong> this account is marked as a bot on some wikis. If it is primarily an automated account (bot), it is <em>not</em> eligible.";
                    $marked_bot = true;
                }


                ########
                ## >=600 edits before 01 June 2010
                ########
                $edits = $script->edit_count(NULL, 20100601000000);
                $prior_edits += $edits;
                $script->condition(
                    $edits >= 600,
                    "has 600 edits before 01 June 2010 (has {$edits})...",
                    "does not have 600 edits before 01 June 2010 (has {$edits}). {$edits_fail_append}",
                    "",
                    $edits_fail_attrs
                );
                if (!$script->eligible) {
                    if (!$script->unified) {
                        continue;
                    }
                    $combining = true;
                }

                ########
                ## >=50 edits between 2010-Mar-01 and 2010-Aug-31
                ########
                $edits = $script->edit_count(20100300000000, 20100900000000);
                $recent_edits += $edits;
                $script->condition(
                    $edits >= 50,
                    "has 50 edits between 01 March 2010 and 31 August 2010 (has {$edits})...",
                    "does not have 50 edits between 01 March 2010 and 31 August 2010 (has {$edits}). {$edits_fail_append}",
                    "",
                    $edits_fail_attrs
                );
                if (!$script->eligible) {
                    if (!$script->unified) {
                        continue;
                    }
                    $combining = true;
                }

                ########
                ## Exit conditions
                ########
                $script->eligible = $prior_edits >= 600 && $recent_edits >= 50;

                /* unified met requirements */
                if ($script->unified && !$script->IsQueueEmpty()) {
                    if ($script->eligible) {
                        break;
                    }
                    $combining = true;
                }
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2010 steward elections, September (candidates)
        ############################
        case 10:
            ########
            ## Has an account on Meta
            ########
            if ($script->wiki == 'metawiki_p' || in_array('metawiki_p', $script->queue)) {
                $on_meta = true;
            }
            else {
                $script->db->Connect('metawiki_p');
                $script->db->Query(
                    "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                    Array($script->user['name'])
                );
                $on_meta = $script->db->fetchColumn();
                $script->db->ConnectPrevious();
            }

            $script->condition(
                $on_meta,
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            if (!$script->eligible) {
                break;
            }


            ########
            ## Has a global account
            ########
            $script->condition(
                $script->is_global(),
                "has a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>...",
                "does not have a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>..."
            );
            if (!$script->eligible) {
                break;
            }

            ########
            ## Check local requirements
            ########
            $script->printWiki();
            do {
                $script->eligible = true;

                ########
                ## Registered before 2010-Mar-29
                ########
                $script->eligible = true;
                $script->condition(
                    $script->user['registration_raw'] < 20100329000000,
                    "has an account registered before 29 March 2010 (registered {$script->user['registration']})...",
                    "does not have an account registered before 29 March 2010 (registered $script->user['registration'])."
                );
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2010 Commons Picture of the Year 2009
        ############################
        case 9:
            $date_okay = false;
            $edits_okay = false;

            $script->printWiki();
            do {
                ########
                ## registered < 2010-Jan-01
                ########
                if (!$date_okay) {
                    $script->condition(
                        $date_okay = ($script->user['registration_raw'] < 20100101000000),
                        "has an account registered before 01 January 2010 (registered {$script->user['registration']})...",
                        "does not have an account registered before 01 January 2010 (registered {$script->user['registration']})."
                    );
                }

                ########
                ## >= 200 edits before 2010-Jan-16
                ########
                if (!$edits_okay) {
                    $edits = $script->edit_count(NULL, 20100116000000);
                    $script->condition(
                        $edits_okay = ($edits >= 200),
                        "has 200 edits before 16 January 2010 (has {$edits})...",
                        "does not have 200 edits before 16 January 2010 (has {$edits})."
                    );
                }
            }
            while ((!$date_okay || !$edits_okay) && $script->get_next());
            $script->eligible = ($date_okay && $edits_okay);
            break;


        ############################
        ## 2010 steward elections, February
        ############################
        case 8:
            ########
            ## Has an account on Meta
            ########
            if ($script->wiki == 'metawiki_p' || in_array('metawiki_p', $script->queue)) {
                $on_meta = true;
            }
            else {
                $script->db->Connect('metawiki_p');
                $script->db->Query(
                    "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                    Array($script->user['name'])
                );
                $on_meta = $script->db->fetchColumn();
                $script->db->ConnectPrevious();
            }

            $script->condition(
                $on_meta,
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            if (!$script->eligible) {
                break;
            }

            ########
            ## Has a global account (optional)
            ########
            $script->condition(
                $script->is_global(),
                "has a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>...",
                "does not have a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a> (<strong>optional</strong>)...",
                "",
                "is-warn"
            );


            ########
            ## Check local requirements
            ########
            $script->printWiki();

            /* set messages for global accounts */
            if ($script->unified) {
                $edits_fail_append = "However, edits will be combined with other unified wikis.";
                $edits_fail_attrs = "is-warn";
            }
            else {
                $edits_fail_append = '';
                $edits_fail_attrs = '';
            }

            /* check requirements */
            $prior_edits = 0;
            $recent_edits = 0;
            $combining = false;
            do {
                ########
                ## Should not be a bot
                ########
                $script->condition(
                    !$script->has_role('bot'),
                    "no bot flag...",
                    "has a bot flag &mdash; the global account must not be primarily automated (bot), but I can't check this so won't mark ineligible.",
                    "",
                    "is-warn"
                );
                $script->eligible = true;
                if ($script->has_role('bot')) {
                    $script->event['append_eligible'] = "<br /><strong>Note:</strong> this account is marked as a bot on some wikis. If it is primarily an automated account (bot), it is <em>not</em> eligible.";
                }


                ########
                ## >=600 edits before 2009-Nov-01
                ########
                $edits = $script->edit_count(NULL, 20091101000000);
                $prior_edits += $edits;
                $script->condition(
                    $edits >= 600,
                    "has 600 edits before 01 November 2009 (has {$edits})...",
                    "does not have 600 edits before 01 November 2009 (has {$edits}). {$edits_fail_append}",
                    "",
                    $edits_fail_attrs
                );
                if (!$script->eligible) {
                    if (!$script->unified) {
                        continue;
                    }
                    $combining = true;
                }

                ########
                ## >=50 edits between 2009-Aug-01 and 2010-Jan-31
                ########
                $edits = $script->edit_count(20090801000000, 20100200000000);
                $recent_edits += $edits;
                $script->condition(
                    $edits >= 50,
                    "has 50 edits between 01 August 2009 and 31 January 2010 (has {$edits})...",
                    "does not have 50 edits between 01 August 2009 and 31 January 2010 (has {$edits}). {$edits_fail_append}",
                    "",
                    $edits_fail_attrs
                );
                if (!$script->eligible) {
                    if (!$script->unified) {
                        continue;
                    }
                    $combining = true;
                }

                ########
                ## Exit conditions
                ########
                $script->eligible = $prior_edits >= 600 && $recent_edits >= 50;

                /* unified met requirements */
                if ($script->unified && !$script->IsQueueEmpty()) {
                    if ($script->eligible) {
                        break;
                    }
                    $combining = true;
                }
            }
            while (!$script->eligible && $script->get_next());


            ########
            ## Add requirement for non-unified accounts
            ########
            if ($script->eligible && !$script->unified) {
                $script->event['more_reqs'][] = "If you do not have a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>, your user page on Meta must link to your main user page, and your main user page must link your Meta user page.";
            }


            ########
            ## Print message about combined edits
            ########
            if ($script->eligible) {
                if ($script->unified && $combining) {
                    $script->msg("<br />Met edit requirements.");
                }
            }
            else {
                if ($script->unified && $combining) {
                    $script->msg("<br />Combined edits did not meet edit requirements.");
                }
                elseif ($script->is_global())
                {
                    $script->event['append_ineligible'] = "<br /><strong>But wait!</strong> This is a global account, which is eligible to combine edits across wikis to meet the requirements. Select 'auto-select wiki' above to combine edits.";
                }
            }
            break;


        ############################
        ## 2010 steward elections, February (candidates)
        ############################
        case 7:
            ########
            ## Has an account on Meta
            ########
            if ($script->wiki == 'metawiki_p' || in_array('metawiki_p', $script->queue)) {
                $on_meta = true;
            }
            else {
                $script->db->Connect('metawiki_p');
                $script->db->Query(
                    "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                    Array($script->user['name'])
                );
                $on_meta = $script->db->fetchColumn();
                $script->db->ConnectPrevious();
            }

            $script->condition(
                $on_meta,
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            if (!$script->eligible) {
                break;
            }


            ########
            ## Has a global account
            ########
            $script->condition(
                $script->is_global(),
                "has a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>...",
                "does not have a <a href='http://meta.wikimedia.org/wiki/Help:Unified_login' title='about global accounts'>global account</a>..."
            );
            if (!$script->eligible) {
                break;
            }

            ########
            ## Check local requirements
            ########
            $script->printWiki();
            do {
                $script->eligible = true;

                ########
                ## Registered before 2009-Oct-28
                ########
                $script->eligible = true;
                $script->condition(
                    $script->user['registration_raw'] < 20091029000000,
                    "has an account registered before 29 October 2009 (registered {$script->user['registration']})...",
                    "does not have an account registered before 29 October 2009 (registered $script->user['registration'])."
                );
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2010 global sysops vote
        ############################
        case 6:
            $age_okay = false;
            $edits_okay = false;

            $script->printWiki();
            do {
                ########
                ## Registered (on any wiki) before 2009-Oct
                ########
                if (!$age_okay) {
                    $age_okay = $script->condition(
                        $script->user['registration_raw'] <= 20091001000000,
                        "has an account registered before 01 October 2009, on any wiki (registered {$script->user['registration']})...",
                        "does not have an account registered before 01 October 2009, on any wiki (registered {$script->user['registration']})."
                    );
                }


                ########
                ## >=150 edits (on any wiki) before start of vote (2010-Jan-01)
                ########
                if (!$edits_okay) {
                    $edits = $script->edit_count(NULL, 20100101000000);
                    $edits_okay = $script->condition(
                        $edits >= 150,
                        "has 150 edits before 01 January 2010, on any wiki (has {$edits})...",
                        "does not have 150 edits before 01 January 2010, on any wiki (has {$edits})."
                    );

                    if (!$edits_okay && $script->user['editcount'] < 150) {
                        break;
                    } // no other wiki can qualify (sorted by edit count)
                }
            }
            while ((!$age_okay || !$edits_okay) && $script->get_next());

            $script->eligible = $age_okay && $edits_okay;
            break;


        ############################
        ## 2009 enwiki arbcom elections
        ############################
        case 5:
            $script->printWiki();

            ########
            ## >=150 main-NS edits before 2009-Nov-02
            ########
            /* SQL derived from query written by [[en:user:Cobi]], from < http://toolserver.org/~sql/sqlbot.txt > */
            $script->db->Query(
                "SELECT data.count FROM ("
                . "SELECT IFNULL(page_namespace, 0) AS page_namespace, IFNULL(SUM(rev.count), 0) AS count FROM {$script->wiki}.page, ("
                . "SELECT rev_page, COUNT(*) AS count FROM {$script->wiki}.revision WHERE rev_user=? AND rev_timestamp<? GROUP BY rev_page"
                . ") AS rev WHERE rev.rev_page=page_id AND page_namespace=0"
                . ") AS data, toolserver.namespace AS toolserver WHERE ns_id=page_namespace AND dbname='enwiki_p'",
                Array($script->user['id'], 20091102000000)
            );
            $edits = $script->db->fetchColumn();

            $script->condition(
                $edits >= 150,
                "has 150 main-namespace edits on or before 01 November 2009 (has {$edits}).",
                "does not have 150 main-namespace edits on or before 01 November 2009 (has {$edits})."
            );
            break;


        ############################
        ## 2009 Commons Picture of the Year 2008
        ############################
        case 4:
            $script->printWiki();
            do {
                $script->eligible = true;

                ########
                ## registered < 2009-Jan-01
                ########
                $script->condition(
                    $script->user['registration_raw'] < 20090101000000,
                    "has an account registered before 01 January 2009 (registered {$script->user['registration']})...",
                    "does not have an account registered before 01 January 2009 (registered {$script->user['registration']})."
                );
                if (!$script->eligible) {
                    continue;
                }

                ########
                ## >= 200 edits before 2009-Feb-12
                ########
                $edits = $script->edit_count(NULL, 20090212000000);
                $script->condition(
                    $edits >= 200,
                    "has 200 edits before 12 February 2009 (has {$edits})...",
                    "does not have 200 edits before 12 February 2009 (has {$edits})."
                );
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2009 steward elections (candidates)
        ############################
        case 3:
            ########
            ## Has an account on Meta
            ########    
            $script->db->Connect('metawiki_p');
            $script->db->Query(
                "SELECT user_id FROM metawiki_p.user WHERE user_name = ?",
                Array($script->user['name'])
            );
            $script->condition(
                $script->db->fetchColumn(),
                "has an account on Meta...",
                "does not have an account on Meta."
            );
            $script->db->ConnectPrevious();
            if (!$script->eligible) {
                break;
            }


            ########
            ## Registered before 2008-Nov-01
            ########
            $script->printWiki();
            do {
                $script->eligible = true;
                $script->condition(
                    $script->user['registration_raw'] <= 20081101000000,
                    "has an account registered before 01 November 2008 (registered {$script->user['registration']})...",
                    "does not have an account registered before 01 November 2008 (registered $script->user['registration'])."
                );
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2009 steward elections
        ############################
        case 2:
            ########
            ## Must not be blocked on Meta
            ########
            $script->db->Connect('metawiki_p');
            $script->db->Query(
                "SELECT COUNT(ipb_expiry) FROM metawiki_p.ipblocks WHERE ipb_user=(SELECT user_id FROM metawiki_p.user WHERE user_name=? LIMIT 1) AND ipb_expiry='infinity' LIMIT 1",
                Array($script->user['name'])
            );
            $script->condition(
                !$script->db->fetchColumn(),
                'is not blocked on Meta...',
                'is blocked on Meta.'
            );
            if (!$script->eligible) {
                break;
            }
            $script->db->ConnectPrevious();


            ########
            ## Check local requirements
            ########
            $script->printWiki();
            do {
                $script->eligible = true;

                ########
                ## Must not be a bot
                ########
                $script->condition(
                    !$script->has_role('bot'),
                    "no bot flag...",
                    "has a bot flag."
                );
                if (!$script->eligible) {
                    continue;
                }

                ########
                ## Registered before 20090101
                ########
                $script->condition(
                    $script->user['registration_raw'] <= 20090101000000,
                    "has an account registered before 01 January 2009 (registered {$script->user['registration']})...",
                    "does not have an account registered before 01 January 2009 (registered {$script->user['registration']})."
                );
                if (!$script->eligible) {
                    continue;
                }

                ########
                ## >=600 edits before 2008-Nov-01
                ########
                $edits = $script->edit_count(NULL, 20081101000000);
                $script->condition(
                    $edits >= 600,
                    "has 600 edits before 01 November 2008 (has {$edits})...",
                    "does not have 600 edits before 01 November 2008 (has {$edits})."
                );
                if (!$script->eligible) {
                    continue;
                }

                ########
                ## >=50 edits between 2008-Aug-01 and 2009-Jan-31
                ########
                $edits = $script->edit_count(20080801000000, 20090131000000);
                $script->condition(
                    $edits >= 50,
                    "has 50 edits between 01 August 2008 and 31 January 2009 (has {$edits})...",
                    "does not have 50 edits between 01 August 2008 and 31 January 2009 (has {$edits})."
                );

                /* exit if no other account can qualify */
                if ($script->user['editcount'] < 600) {
                    break;
                }
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## 2008 enwiki arbcom elections
        ############################
        case 1:
            $script->printWiki();

            ########
            ## >=150 main-NS edits before 2008-Nov-02
            ########
            /* SQL derived from query written by [[en:user:Cobi]], from < http://toolserver.org/~sql/sqlbot.txt > */
            $script->db->Query(
                "SELECT data.count FROM ("
                . "SELECT IFNULL(page_namespace, 0) AS page_namespace, IFNULL(SUM(rev.count), 0) AS count FROM {$script->wiki}.page, ("
                . "SELECT rev_page, COUNT(*) AS count FROM {$script->wiki}.revision WHERE rev_user=? AND rev_timestamp<? GROUP BY rev_page"
                . ") AS rev WHERE rev.rev_page=page_id AND page_namespace=0"
                . ") AS data, toolserver.namespace AS toolserver WHERE ns_id=page_namespace AND dbname='enwiki_p'",
                Array($script->user['id'], 20081102000000)
            );

            $edits = $script->db->fetchColumn();
            $script->condition(
                $edits >= 150,
                "has 150 main-namespace edits on or before 01 November 2008 (has {$edits}).",
                "does not have 150 main-namespace edits on or before 01 November 2008 (has {$edits})."
            );

            break;


        ############################
        ## 2008 Board elections
        ############################
        case 16:
            $script->printWiki();
            do {
                $script->eligible = true;

                ########
                ## Not indefinitely blocked
                ########
                $script->condition(
                    !$script->indef_blocked(),
                    "not indefinitely blocked...",
                    "indefinitely blocked."
                );
                if (!$script->eligible) {
                    continue;
                }

                ########
                ## Not a bot
                ########
                $script->condition(
                    !$script->has_role('bot'),
                    "no bot flag...",
                    "has a bot flag."
                );
                if (!$script->eligible) {
                    continue;
                }

                ########
                ## >=600 edits before 2008-Mar
                ########
                $edits = $script->edit_count(NULL, 20080301000000);
                $script->condition(
                    $edits >= 600,
                    "has 600 edits before 01 March 2008 (has {$edits})...",
                    "does not have 600 edits before 01 March 2008 (has {$edits})."
                );
                if (!$script->eligible) {
                    continue;
                }

                ########
                ## >=50 edits between 2008-Jan and 2008-Jun
                ########
                $edits = $script->edit_count(20080101000000, 20080529000000);
                $script->condition(
                    $edits >= 50,
                    "has 50 edits between 01 January 2008 and 29 May 2008 (has {$edits})...",
                    "does not have 50 edits between 01 January 2008 and 29 May 2008 (has {$edits})."
                );

                ########
                ## Exit conditions
                ########
                /* eligible */
                if ($script->eligible) {
                    break;
                }

                /* no other accounts can be eligible */
                if ($script->user['editcount'] < 600) {
                    $script->eligible = false;
                    break;
                }
            }
            while (!$script->eligible && $script->get_next());
            break;


        ############################
        ## No such event
        ############################
        default:
            echo '<div class="fail">No such event.</div>';
    }


    ############################
    ## Print result
    ############################
    if ($script->event) {
        ########
        ## Script results
        ########
        $event = $script->event;
        $action = isset($event['action']) ? $event['action'] : 'vote';
        $class = $script->eligible ? 'success' : 'fail';
        $name = "{$script->user['name']}@" . ($script->unified ? 'global' : $script->wiki);

        echo "<h2>Result</h2><div class='{$class}' id='result' data-is-eligible='", ($script->eligible ? 1 : 0), "'>{$name} is ",
        ($script->eligible ? '' : 'not '),
        "eligible to {$action} in the <a href='", $event['url'], "' title='", $backend->FormatFormValue($event['name']), "'>", $event['name'], "</a>. ";

        if ($script->eligible && isset($script->event['append_eligible'])) {
            echo $script->event['append_eligible'];
        }
        elseif (!$script->eligible && isset($script->event['append_ineligible']))
        {
            echo $script->event['append_ineligible'];
        }

        echo "</div>";

        ########
        ## Mention additional requirements
        ########
        if ($script->eligible && isset($script->event['more_reqs'])) {
            echo "<div class='error' style='border-color:#CC0;'><strong>There are additional requirements</strong> that cannot be checked by this script:<ul style='margin:0;'>";
            foreach ($script->event['more_reqs'] as $req)
                echo "<li>{$req}</li>";
            echo "</lu></div>";
        }
    }
  }
  ?>
